//
//  Status.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/8/1.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SDWebImage
class Status: NSObject {

    //	微博创建时间
    var created_at: String?
    // 微博ID
    var id : Int = 0
    // 微博信息内容
    var text: String?
    // 微博来源
    var source: String?
    //配图数组
    var pic_urls: [[String: AnyObject]]? {
        
        didSet {
            
            if pic_urls!.count == 0{
                return
            }
            storedPictureURLs = [NSURL]()
            storedLargePictureURLs = [NSURL]()
            
            for dict in pic_urls! {
            
                if let urlString = dict["thumbnail_pic"] as? String {
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                    
                    let urlLargeString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    storedLargePictureURLs?.append(NSURL(string: urlLargeString)!)
                }
            }
            
        }
    }
    
    var storedPictureURLs: [NSURL]?
    var storedLargePictureURLs: [NSURL]?
    //添加图片的地址
    var pictureURLs: [NSURL]?{
        
        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }
    var largepictureURLs: [NSURL]? {
        
        return retweeted_status == nil ? storedLargePictureURLs : retweeted_status?.storedLargePictureURLs
    }
    //行高
    var rowHeight: CGFloat?
    // 添加用户属性
    var user: User?
    
    //添加转发微博属性
    var retweeted_status: Status?
    
    class func loadStatus(since_id:Int,max_id: Int,finished:(datalist:[Status]?, error: NSError?) ->()) {
        
        //尾随闭包
        NetWorkTools.sharedTools.loadStatus(since_id, max_id: max_id){ (result, error) -> () in
            
            if error != nil {
                finished(datalist: nil, error: error)
                return
            }
            
            if let array = result?["statuses"] as?[[String: AnyObject]] {
                
                var list = [Status]()
                
                for dict in array {
                    
                    list.append(Status(dict: dict))
                }
                
               self.cacheWebImage(list, finished: finished)
            }else {
                finished(datalist: nil, error: nil)
        }
    }
}
    
    private class func cacheWebImage(list:[Status],finished:(datalist:[Status]?, error: NSError?) ->()) {
        
        let group = dispatch_group_create()
        var datalength  = 0
        for status in list {
            guard let urls = status.pictureURLs else {
                continue
            }
            
            for imageUrl in urls {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _ , _ , _, _) -> Void in
                    
                    if image != nil {
                        
                        let data = UIImagePNGRepresentation(image)!
                        datalength += data.length
                    }
                    
                   
                    
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            
            finished(datalist: list, error: nil)
        }
    }
    
    init(dict: [String: AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        
        if key == "user" {
            if let dict = value as?[String: AnyObject] {
                
                user = User(dict: dict)
            }
            
            return
        }
        if key == "retweeted_status" {
            if let dict = value as?[String: AnyObject] {
                
                retweeted_status = Status(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description: String {
        let keys = ["created_at","id","text","source","pic_urls"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
}
